package com.example.ourdut

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.webkit.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


const val URL_WITH_HTTPS = "https://www.ourdut.com"
const val URL_WITHOUT_HTTPS = "www.ourdut.com"

class MainActivity : AppCompatActivity() {


    private lateinit var webView: WebView
    private lateinit var webSettings: WebSettings

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        webView = findViewById<WebView>(R.id.web_view).apply {
            loadUrl(URL_WITH_HTTPS)
            Log.d("zzh", "loadUrl:" + url + " host is " + Uri.parse(url).host)
            webViewClient = object : WebViewClient() {
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    Log.d("zzh", "onPageStarted")
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    Log.d("zzh", "onPageFinished")
                }

                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    if (url == null) {
                        Log.d("zzh", "urlNull")
                        return false
                    }
                    try {
                        if (!url.startsWith("http://") && !url.startsWith("https://")) {
                            Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
                                startActivity(this)
                                Log.d("zzh","not http/https")
                            }
                            return true
                        } else if (Uri.parse(url).host == URL_WITHOUT_HTTPS) {
                            view?.loadUrl(url)
                            Log.d("zzh", "isHost "+"loadUrl:" + url + " host is " + Uri.parse(url).host)
                            return false
                        } else {
                            view?.loadUrl(url)
                            Log.d("zzh", "loadUrl:" + url + " host is " + Uri.parse(url).host)
                            return true
                        }
                    } catch (e: Exception) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                        return true//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                    }
                }
            }
            webChromeClient = object : WebChromeClient() {
                override fun onProgressChanged(view: WebView, newProgress: Int) {
                    super.onProgressChanged(view, newProgress)
                    Log.d("zzh", "onProgressChanged:" + newProgress)

                }

                override fun onReceivedTitle(view: WebView, title: String) {
                    super.onReceivedTitle(view, title)
                    Log.d("zzh", "onReceivedTitle")
                }
            }
        }

        webSettings = webView.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true

            //设置自适应屏幕，两者合用
            useWideViewPort = true //将图片调整到适合webview的大小
            loadWithOverviewMode = true // 缩放至屏幕的大小

            //缩放操作
            setSupportZoom(true) //支持缩放，默认为true。是下面那个的前提。
            builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放
            displayZoomControls = false //隐藏原生的缩放控件

            //其他细节操作
            allowFileAccess = true //设置可以访问文件
            javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
            loadsImagesAutomatically = true //支持自动加载图片
            defaultTextEncodingName = "utf-8" //设置编码格式
            //cacheMode = WebSettings.LOAD_DEFAULT
            cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK //关闭webview中缓存

        }

    }

    override fun onResume() {
        super.onResume()
        //webView.onResume()
        webSettings.javaScriptEnabled = true
    }

    override fun onStop() {
        super.onStop()
        webSettings.javaScriptEnabled = false
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // Check if the key event was the Back button and if there's history
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack()
            return true
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event)
    }


}

